package com.example.service;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.Result;
import com.example.entity.*;
import com.example.entity.Test_User;
import com.example.entity.others.*;
import com.example.mapper.QuestionMapper;
import com.example.mapper.StudentMapper;
import com.example.tool.QuestionGenerator;
import com.mysql.cj.util.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StudentService {
    @Resource
    StudentMapper studentMapper;

    @Resource
    SparkService sparkService;

    @Resource
    QuestionGenerator questionGenerator;

    public Object testList(User_Subject userSubject) {
        List<Test_User> testUsers = studentMapper.getTestUserListByUid(userSubject.getUid());
        List<Test> tests = new ArrayList<>();
        for (Test_User testUser : testUsers) {
            Test test = new Test();
            test = studentMapper.getTestById(testUser);
            if (userSubject.getSubject()==null || test.getSubject().equals(userSubject.getSubject())) {
                tests.add(test);
            }
//            tests.add(test);
        }
        return tests;
    }

    public void createAi(Test_User_Other testUserOther) {
        Test test = testUserOther.getTest();
        User user = testUserOther.getUser();

        Test_User testUser = new Test_User();
        //插入test表
        studentMapper.createTest(test);
        //插入test_user表
        testUser.setTid(test.getTid());
        testUser.setUid(user.getUid());
        studentMapper.createTestUser(testUser);

        Date date = new Date();
        Map<String,List<Question>> allMap = questionGenerator.generateQuestionsConcurrently(test,user);
        Date date2 = new Date();

        for (String type : allMap.keySet()){
            List<Question> questionList = allMap.get(type);

            int i = 1;
            for (Question question : questionList){
                question.setQid(i);
                studentMapper.createQuestion(question);

                Question_Student questionStudent = new Question_Student();
                questionStudent.setQid(question.getQid());
                questionStudent.setSid(user.getUid());
                studentMapper.createQuestionStudent(questionStudent);

                i++;
            }
        }

        Date date1 = new Date();
        long differenceInMillis = date1.getTime() - date.getTime();
        long differenceInMillis1 = date1.getTime() - date2.getTime();
        System.out.println(differenceInMillis);
        System.out.println(differenceInMillis1);
    }

    public Object humanQuestion(Test_User_Other testUserOther) {
        Test_Map_Question testMapQuestion = new Test_Map_Question();
        Test test = testUserOther.getTest();

        Map<String, List<Question>> map = new HashMap<>();
        List<Question> questions = new ArrayList<>();
        List<Question> questionsCAll = new ArrayList<>();
        List<Question> questionFAll = new ArrayList<>();
        List<Question> questionSAll = new ArrayList<>();

        List<Test> tests = studentMapper.getTestBySubject(test);
        List<Integer> tidList = tests.stream().map(Test::getTid).collect(Collectors.toList());

        List<Question> questionsC = studentMapper.getAllCByTid(tidList);
        List<Question> questionsF = studentMapper.getAllFByTid(tidList);
        List<Question> questionsS = studentMapper.getAllSByTid(tidList);

        if(testUserOther.getKpoint() != null){
            questionsC =questionsC.stream().filter(x -> Objects.equals(x.getKpoint(), testUserOther.getKpoint())).collect(Collectors.toList());
            questionsF =questionsF.stream().filter(x -> Objects.equals(x.getKpoint(), testUserOther.getKpoint())).collect(Collectors.toList());
            questionsS =questionsS.stream().filter(x -> Objects.equals(x.getKpoint(), testUserOther.getKpoint())).collect(Collectors.toList());
        }

        if(testUserOther.getType() != null){
            questionsC =questionsC.stream().filter(x -> Objects.equals(x.getType(), testUserOther.getKpoint())).collect(Collectors.toList());
            questionsF =questionsF.stream().filter(x -> Objects.equals(x.getType(), testUserOther.getKpoint())).collect(Collectors.toList());
            questionsS =questionsS.stream().filter(x -> Objects.equals(x.getType(), testUserOther.getKpoint())).collect(Collectors.toList());
        }

        if(testUserOther.getContent() != null){
            questionsC =questionsC.stream().filter(x -> Objects.equals(x.getContent(), testUserOther.getKpoint())).collect(Collectors.toList());
            questionsF =questionsF.stream().filter(x -> Objects.equals(x.getContent(), testUserOther.getKpoint())).collect(Collectors.toList());
            questionsS =questionsS.stream().filter(x -> Objects.equals(x.getContent(), testUserOther.getKpoint())).collect(Collectors.toList());
        }



        Integer pageStartNum = testUserOther.getPage() * 10 - 10;
        Integer pageEndNum = testUserOther.getPage() * 10;


        questions.addAll(questionsC);
        questions.addAll(questionsF);
        questions.addAll(questionsS);

        List<Question> questionList = new ArrayList<>();

        if(pageEndNum > questions.size() && pageStartNum < questions.size()){
            return questions.subList(pageStartNum,questions.size());
        }
        questionList = questions.subList(pageStartNum,pageEndNum);

        testMapQuestion.setTotal(questions.size());

        questionsCAll = questionList.stream().filter(x -> x.getType().equals("选择题")).collect(Collectors.toList());
        questionFAll = questionList.stream().filter(x -> x.getType().equals("填空题")).collect(Collectors.toList());
        questionSAll = questionList.stream().filter(x -> x.getType().equals("解答题")).collect(Collectors.toList());

        map.put("选择题", questionsCAll);
        map.put("填空题", questionFAll);
        map.put("解答题", questionSAll);

        Test test1 = new Test();
        test1.setTid(test.getTid());

        testMapQuestion.setQuestionMap(map);
        testMapQuestion.setTest(test1);
        return testMapQuestion;
    }

    public void createHuman(Test_Map_Question testMapQuestion) {
        Question_Student questionStudent = new Question_Student();
        Test test = new Test();

        List<Question> questionCAll = testMapQuestion.getQuestionMap().get("选择题");
        List<Question> questionFAll = testMapQuestion.getQuestionMap().get("填空题");
        List<Question> questionSAll = testMapQuestion.getQuestionMap().get("解答题");

        int i = 0;

        questionStudent.setSid(testMapQuestion.getUser().getUid());
        test.setTid(testMapQuestion.getTest().getTid());

        for (Question question : questionCAll) {
            i++;
            question.setQnum(i);
            question.setTid(test.getTid());

            studentMapper.createQuestion(question);
            questionStudent.setQid(question.getQid());
            studentMapper.createQuestionStudent(questionStudent);
        }

        test.setCnum(i);
        i = 0;

        for (Question question : questionFAll) {
            i++;
            question.setQnum(i);
            question.setTid(test.getTid());

            studentMapper.createQuestion(question);
            questionStudent.setQid(question.getQid());
            studentMapper.createQuestionStudent(questionStudent);
        }

        test.setFnum(i);
        i = 0;

        for (Question question : questionSAll) {
            i++;
            question.setQnum(i);
            question.setTid(test.getTid());

            studentMapper.createQuestion(question);
            questionStudent.setQid(question.getQid());
            studentMapper.createQuestionStudent(questionStudent);
        }

        test.setSnum(i);

        studentMapper.updateTest(test);

    }

    public Object questionAll(int tid,int sid) {
        Map<String, List<User_Question>> map = new HashMap<>();

        List<User_Question> userQuestionC = studentMapper.getUqcByTestid(tid, sid);
        List<User_Question> userQuestionF = studentMapper.getUqfByTestid(tid, sid);
        List<User_Question> userQuestionS = studentMapper.getUqsByTestid(tid, sid);

        map.put("选择题", userQuestionC);
        map.put("填空题", userQuestionF);
        map.put("解答题", userQuestionS);

        return map;
    }

    public Object correctingAi(List<User_Question> userQuestions) {
        String input = "";
        int i = 0;
        for (User_Question userQuestion : userQuestions) {
            if(userQuestion.getUanswer() == null){
                userQuestion.setUanswer("");
            }
            input = input + "QNum: " + userQuestion.getId() + "\n"
                    + "Question: " + userQuestion.getContent() + "\n"
                    + "Answer: " + userQuestion.getAnswer() + "\n"
                    + "UAnswer: " + userQuestion.getUanswer() + "\n";
            i++;
        }

        List<Question_Student> questionStudents = sparkService.correctStuQuestionAi(input, i);
        int sid = userQuestions.get(0).getSid();
        for (Question_Student questionStudent : questionStudents) {
            if("None".equals(questionStudent.getUanswer())){
                questionStudent.setUanswer("");
            }
            questionStudent.setSid(sid);
            studentMapper.updateQSById(questionStudent);
        }


        Map<String, List<User_Question>> map = new HashMap<>();

        List<User_Question> userQuestionC = studentMapper.getUqcByTestid(userQuestions.get(0).getTid(), userQuestions.get(0).getSid());
        List<User_Question> userQuestionF = studentMapper.getUqfByTestid(userQuestions.get(0).getTid(), userQuestions.get(0).getSid());
        List<User_Question> userQuestionS = studentMapper.getUqsByTestid(userQuestions.get(0).getTid(), userQuestions.get(0).getSid());


        map.put("选择题", userQuestionC);
        map.put("填空题", userQuestionF);
        map.put("解答题", userQuestionS);

        return map;
    }

    public Object createAnalysisBySubject(Analysis_Student analysisStudent) {
        int aidname=studentMapper.getAnameSubject(analysisStudent) + 1;
        String aName=analysisStudent.getSubject()+"分析"+aidname;

        analysisStudent.setAname(aName);

        List<Test> tests = studentMapper.getTestBySId(analysisStudent);
        Map<String, True_False_Num> map = new HashMap<>();

        for (Test test : tests) {
            String Kpoint = test.getKpoint();
            True_False_Num trueFalseNum = new True_False_Num();

            int i = studentMapper.getTrueCount(analysisStudent.getSid(), test.getTid());
            int j = studentMapper.getFalseCount(analysisStudent.getSid(), test.getTid());

            trueFalseNum.setTNum(i);
            trueFalseNum.setFNum(j);

            map.compute(Kpoint, (key, existingValue) -> {
                if (existingValue == null) {
                    return trueFalseNum;
                } else {
                    existingValue.setTNum(existingValue.getTNum() + trueFalseNum.getTNum());
                    existingValue.setFNum(existingValue.getFNum() + trueFalseNum.getFNum());
                    return existingValue;
                }
            });
        }

        StringBuilder input = new StringBuilder(new String());

        for (String key : map.keySet()) {
            True_False_Num trueFalseNum = map.get(key);

            input.append("知识点: ").append(key).append("\n");
            input.append("错误数量: ").append(trueFalseNum.getFNum()).append("\n");
            input.append("正确数量: ").append(trueFalseNum.getTNum()).append("\n");
        }

        analysisStudent.setContent(sparkService.correctAnalysisSubject(String.valueOf(input)));

        studentMapper.createAnalysis(analysisStudent);

        List<Analysis_Student> analysisStudents=studentMapper.getAnalysisList(analysisStudent);

        return analysisStudents;
    }

    public Object getAnalysisAll(Analysis_Student analysisStudent) {
        return studentMapper.getAnalysisList(analysisStudent);
    }

    public Object getAnalysis(Analysis_Student analysisStudent) {
        return studentMapper.getAnalysisContent(analysisStudent.getAid());
    }

    public List<JSONObject> listClass(Class_Student classStudent) {
        List<JSONObject> classList = studentMapper.getClassBysid(classStudent);
        return classList;
    }

    public List<JSONObject> joinClass(Class_Student classStudent) {
        Class_Student classStudent1 = studentMapper.getClassOneBysid(classStudent);
        if(classStudent1==null){
            studentMapper.createClass(classStudent);
        }else {
            classStudent.setBelong(1);
            studentMapper.updateClass(classStudent);
        }
        return studentMapper.getClassBysid(classStudent);
    }

    public Object cancelClass(Class_Student classStudent) {
        Class_Student classStudent1 = studentMapper.getClassOneBysid(classStudent);
        if(classStudent1!=null){
            classStudent.setBelong(0);
            studentMapper.updateClass(classStudent);
        }
        return studentMapper.getClassBysid(classStudent);
    }

    public Object testDelete(Test_User testUser) {
        User user = new User();
        Test test = studentMapper.getTestById(testUser);
        user.setUid(testUser.getUid());

        studentMapper.deleteTestUser(testUser);
        List<Question> questions = studentMapper.getAllByTid(test);
        for (Question question : questions) {
            Question_Student questionStudent = new Question_Student();
            questionStudent.setQid(question.getQid());
            questionStudent.setSid(testUser.getUid());
            studentMapper.deleteQuestion(questionStudent);
        }
        User_Subject userSubject = new User_Subject();
        userSubject.setUid(testUser.getUid());
        userSubject.setSubject(test.getSubject());
        return this.testList(userSubject);
    }

    public void doHomework(List<Question_Student> questionStudent) {
        for (Question_Student qs : questionStudent) {
            studentMapper.updateQSById(qs);
        }
    }

    public void questionReset(int tid, int uid) {
        List<Integer> questionId = studentMapper.getQuestionId(tid);
        for (Integer qid : questionId){
            studentMapper.resetQuestion(uid,qid);
        }
    }

    public List<Analysis_Student> getAnalysisList(Analysis_Student analysisStudent) {
        return studentMapper.getAnalysisListAll(analysisStudent);
    }

    public Object deleteAnalysis(Analysis_Student analysisStudent) {
        studentMapper.deleteAnalysis(analysisStudent);
        return studentMapper.getAnalysisList(analysisStudent);
    }

    public List<JSONObject> listParent(Parent_Student parentStudent) {
        return studentMapper.getParentList(parentStudent);
    }

    public void bindParent(Parent_Student parentStudent) {
        Parent_Student data = studentMapper.getparentStudent(parentStudent);
        if(data != null){
            data.setBind(1);
            studentMapper.updateParentStudent(data);
        }else {
            studentMapper.bindParent(parentStudent);
        }
    }

    public void cancelParent(Parent_Student parentStudent) {
        studentMapper.cancelParent(parentStudent);
    }

    public Test createHumanTest(Test_User_Other testUserOther) {
        Test_Map_Question testMapQuestion = new Test_Map_Question();
        Test_User testUser = new Test_User();
        Test test = testUserOther.getTest();
        test.setKpoint("综合");

        studentMapper.createTestByHuman(test);

        User user = testUserOther.getUser();
        testUser.setTid(test.getTid());
        testUser.setUid(user.getUid());
        studentMapper.createTestUser(testUser);
        return test;
    }
}
